package com.fzy.common.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 验证码检验
 *
 * @author 冯赵杨
 * @create 2018/9/26
 */
public class ValidateCodeServlet2 extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public static final String VALIDATE_CODE = "icheckCode";

    private final static Logger logger = LoggerFactory.getLogger(ValidateCodeServlet.class);

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.addDateHeader("Expires", 0);
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");
        sendImage(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    public String getRandomNumber(int len) {
        char[] cs = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNOPQRSTUVWXYZ".toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            char c = cs[(int) (Math.random() * 48)];
            sb.append(c);
        }
        return sb.toString();
    }

    private void sendImage(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");
            ServletOutputStream sos = response.getOutputStream();
            // 在内存中创建图象
            int width = 80, height = 25;
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 获取图形上下文
            Graphics g = image.getGraphics();

            //生成随机类
            Random random = new Random();

            // 设定背景色
            g.setColor(getRandColor(240, 250));
            g.fillRect(0, 0, width, height);

            //设定字体
            g.setFont(new Font("Times New Roman", Font.PLAIN, 20));

            // 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
            g.setColor(getRandColor(180, 230));
            for (int i = 0; i < 10; i++) {
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int xl = random.nextInt(12);
                int yl = random.nextInt(12);
                g.drawLine(x, y, x + xl, y + yl);
            }
            //验证码，由2个一位数的加减法构成，例如：3 + 4 = ？
            int num1 = (int) (Math.random() * 10);
            int num2 = (int) (Math.random() * 10);
            //random.nextInt(3);  //产生[0,2]之间的随机整数
            int funNo = 0;
            String funMethod = "";
            int result = 999;
            switch (funNo) {
                case 0:
                    funMethod = "+";
                    result = num1 + num2;
                    break;
                case 1:
                    funMethod = "- ";
                    result = num1 - num2;
                    break;
                case 2:
                    funMethod = "×";
                    result = num1 * num2;
                    break;
                default:
                    break;
            }
            String calc = num1 + " " + funMethod + " " + num2 + " = ?";
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            //绘制边距
            g.drawString(calc, 5, 20);
            // 将认证码存入SESSION
            request.getSession().setAttribute(VALIDATE_CODE, String.valueOf(result));
            // 图象生效
            g.dispose();
            // 输出图象到页面
            ImageIO.write(image, "JPEG", response.getOutputStream());
            sos.close();
        } catch (IOException e) {
            logger.error("error", e);
        }
    }

    /**
     * 给定范围获得随机颜色
     *
     * @param fc
     * @param bc
     * @return
     * @author 冯赵杨
     */
    public Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

}
